<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>聊天室</title>
    <meta name="description" content="这是一个 index 页面">
    <meta name="keywords" content="index">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="icon" type="image/png" href="assets/i/favicon.png">
    <link rel="apple-touch-icon-precomposed" href="assets/i/app-icon72x72@2x.png">
    <meta name="apple-mobile-web-app-title" content="Amaze UI" />
    <link rel="stylesheet" href="assets/css/amazeui.min.css" />
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="stylesheet" href="assets/css/gb_my.css">
    <link rel="stylesheet" href="assets/css/font-awesome.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body data-type="chart">
<div id="wrapper">
    <!--头部-->
    <nav class="navbar navbar-default top-navbar">
        <div class="navbar-header">
            <a class="navbar-brand waves-effect waves-dark" href="javascript:;">
                <img src="assets/img/logo.png" alt="">
                <strong>轻课网考试系统</strong>
            </a>
            <div id="sideNav" href="">
                <i class="mulv QK QK-mulu"></i>
            </div>
        </div>

        <ul class="nav navbar-top-links navbar-right aaa">
            <li>
                <a id="down_" class="sign-out dropdown-button waves-effect waves-dark" href="javascript:;">
                    <span class="am-icon-sign-out"></span> 退出
                </a>
            </li>
            <li>
                <a class="dropdown-button waves-effect waves-dark" href="javascript:;"><b>欢迎你, <span class="userName"></span> </b></a>
            </li>
        </ul>
    </nav>
    <!--导航栏-->
    <nav class="navbar-default navbar-side">
        <div class="sidebar-collapse">
            <!--用户头像-->
            <div class="tpl-sidebar-user-panel">
                <div class="tpl-user-panel-slide-toggleable">
                    <div class="tpl-user-panel-profile-picture">
                        <img src="assets/img/user04.png" alt="">
                    </div>
                </div>
            </div>
            <dl class="list_dl">
                <dt class="list_dt">
                    <a href="index.html">
                        <span class="QK1 start_before"></span>
                        <p>学生平台</p>
                    </a>
                </dt>
                <dt class="list_dt">
                    <span class="QK1 topic_before"></span>
                    <p>我的考试</p>
                    <i class="QK1 list_dt_icon"></i>
                </dt>
                <dd class="list_dd">
                    <ul>
                        <li class="list_li">
                            <a href="student.html">我的试卷</a>
                        </li>
                        <li class="list_li">
                            <a href="examRecords.html">考试记录</a>
                        </li>
                    </ul>
                </dd>
                <dt class="list_dt">
                    <span class="QK1 paper_before"></span>
                    <p>自我检测</p>
                    <i class="QK1 list_dt_icon"></i>
                </dt>
                <dd class="list_dd">
                    <ul>
                        <li class="list_li">
                            <a href="testing.html">自我检测</a>
                        </li>
                        <li class="list_li">
                            <a href="error.html">检测结果</a>
                        </li>
                    </ul>
                </dd>
                <dt class="list_dt">
                    <span class="QK1 user_before"></span>
                    <p>个人管理</p>
                    <i class="QK1 list_dt_icon"></i>
                </dt>
                <dd class="list_dd">
                    <ul>
                        <li class="list_li">
                            <a href="personalData.html">个人资料</a>
                        </li>
                        <li class="list_li">
                            <a href="collection.html">题目收藏</a>
                        </li>
                    </ul>
                </dd>
                <dt id="open" class="list_dt">
                    <span class="QK1 chat_before"></span>
                    <p>聊天室</p>
                    <i class="QK1 list_dt_icon"></i>
                </dt>
                <dd class="list_dd" style="display: block">
                    <ul>
                        <li class="list_li" id="style_li_a">
                            <a href="chatroom.html">聊天室</a>
                        </li>
                    </ul>
                </dd>
            </dl>
        </div>
    </nav>
    <!-- 内容区域 -->
    <div id="page-wrapper">
			<div class="chatbox">
  <div class="chat_top fn-clear">
    <div class="logo">
      <img src="assets/img/chat.png" alt=""/>
    </div>
  </div>
  <div class="chat_message fn-clear">
    <div class="chat_left only_left">
      <div class="message_box" id="message_box">

      </div>
      <div class="write_box">
        <textarea id="message" name="message" class="write_area" placeholder="说点啥吧..."></textarea>
        <div class="btn_submit">
            <button name="" class="sub_but">发 送</button>
        </div>
      </div>
    </div>
  </div>
</div>
    </div>
</div>
</body>
</html>
<script src="assets/js/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.cookie.js"></script>
<script src="assets/js/theme.js"></script>
<script src="assets/js/amazeui.min.js"></script>
<script src="assets/js/amazeui.datatables.min.js"></script>
<script src="assets/js/dataTables.responsive.min.js"></script>
<script src="assets/js/student.js"></script>
<script>
    $(document).ready(function () {
        $(".list_dt").on("click",function () {
            $('.list_dd').stop();
            $(this).siblings("dt").removeAttr("id");
            if($(this).attr("id")=="open"){
                $(this).removeAttr("id").siblings("dd").slideUp();//slideup隐藏 slidedowm显示
            }else{
                $(this).attr("id","open").next().slideDown().siblings("dd").slideUp();
            }
        });
    });
</script>
<script>
    $(document).ready(function () {
        $(".dropdown-button").dropdown();
        $("#sideNav").click(function(){
            if($(this).hasClass('closed')){
                $('.navbar-side').animate({left: '0px'});
                $(this).removeClass('closed');
                $('#page-wrapper').animate({'margin-left' : '260px'});
            }
            else{
                $(this).addClass('closed');
                $('.navbar-side').animate({left: '-260px'});
                $('#page-wrapper').animate({'margin-left' : '0px'});
            }
        });
    });
    $(".dropdown-button").dropdown();
</script>
<script type="text/javascript">
$(document).ready(function(e) {
	$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
	$('.uname').hover(
	    function(){
		    $('.managerbox').stop(true, true).slideDown(100);
	    },
		function(){
		    $('.managerbox').stop(true, true).slideUp(100);
		}
	);
	var fromname = $('#fromname').val();

//	var userName_judge = true;
//	if(userName_judge){
//
//    }else{
//
//    }
	
	$('.sub_but').click(function(event){
	    send();
	});
	
	/*按下按钮或回车*/
	$("#message").keydown(function(event){
		var e = window.event || event;
        var k = e.keyCode || e.which || e.charCode;
		//按下ctrl+enter发送消息
//		if((event.ctrlKey && (k == 13 || k == 10) )){
        //按下回车发送消息
		if((k == 13 || k == 10)){
			send();
		}
	});
});
/*function sendMessage(event, from_name){
    var msg = $("#message").val();
	var htmlData =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><img src="images/hetu.jpg" width="40" height="40"  alt=""/></div>'
			       + '   <div class="item_right">'
                   + '   <div class="name_time">' + from_name + ' · 30秒前</div>'
                   + '   <div class="msg own">' + msg + '</div>'
			       + '   </div>'
			       + '</div>';
	$("#message_box").append(htmlData);
	$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
	$("#message").val('');
}*/
</script>
<script type="text/javascript">
	var storage = window.localStorage;
        var uid = storage["uid"];
        var userName = storage["user_name"];
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://47.97.8.254:8080/QingKeExam/websocket");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //连接成功建立的回调方法
    websocket.onopen = function () {
    	console.log(event)
        //setMessageInnerHTML("WebSocket连接成功");
    };

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    };

    //连接关闭的回调方法
    websocket.onclose = function (event) {
        //setMessageInnerHTML("WebSocket连接关闭");
        console.log(event)
    };
    
    //连接发生错误的回调方法
    websocket.onerror = function () {
    	console.log(event)
        //setMessageInnerHTML("WebSocket连接发生错误");
    };

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    };
    $.ajax({
        url: localApi + "/ChatROOM/index",
        type: "get",
        async: false,
        data: {
            apikey:'1'
        },
        success:function(result){
//            console.log(result.data);
					result.data.reverse();
            $.each(result.data , function (n , item) {
                console.log(item);
				
                if(item.student.sid != uid){
                    var htmlData =   '<div class="msg_item fn-clear">'
                        + '   <div class="uface"><span>'+ item.student.name +'</span><img src="assets/img/hetu.jpg" width="30" height="30"  alt=""/></div>'
                        + '   <div class="item_right">'
                        + '   <div class="name_time">' + formatDate(item.createTime)+'</div>'
                        + '   <div class="msg_triangle_1"></div>'
                        + '   <div class="msg own">' + item.content + '</div>'
                        + '   </div>'
                        + '</div>';
                    $("#message_box").append(htmlData);
                }else{
                    var htmlData2 =   '<div class="msg_item_oneSelf fn-clear">'
                        + '   <div class="uface_oneSelf"><span>'+ item.student.name +'</span><img src="assets/img/hetu.jpg" width="30" height="30"  alt=""/></div>'
                        + '   <div class="item_oneSelf">'
                        + '   <div class="name_time_oneSelf">' + formatDate(item.createTime)+'</div>'
                        + '   <div class="msg_triangle"></div>'
						+ '   <div class="msg_oneSelf own_oneSelf">' + item.content + '</div>'
                        + '   </div>'
                        + '</div>';
                    $("#message_box").append(htmlData2);
                }
            })
        }
    });

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        var work4=eval("(" + innerHTML + ")");
        console.log(work4);
        console.log(uid);
        if(work4.uid  != uid){
        var htmlData =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><span>'+ work4.formName +'</span><img src="assets/img/hetu.jpg" width="30" height="30"  alt=""/></div>'
			       + '   <div class="item_right">'
                   + '   <div class="name_time">' + formatDate(work4.createTime)+'</div>'
                   + '   <div class="msg_triangle_1"></div>'
                   + '   <div class="msg own">' + work4.content + '</div>'
                   + '   </div>'
                   + '</div>';
        $("#message_box").append(htmlData);
        }else{
            var htmlData2 =   '<div class="msg_item_oneSelf fn-clear">'
                + '   <div class="uface_oneSelf"><span>'+ userName +'</span><img src="assets/img/hetu.jpg" width="30" height="30"  alt=""/></div>'
                + '   <div class="item_oneSelf">'
                + '   <div class="name_time_oneSelf">' + formatDate(work4.createTime)+'</div>'
				+ '   <div class="msg_triangle"></div>'
                + '   <div class="msg_oneSelf own_oneSelf">' + work4.content + '</div>'                
                + '   </div>'
                + '</div>';
            $("#message_box").append(htmlData2);
			$("#message").val('');
        }
        $('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
        
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var msg = $("#message").val();
        console.log(msg);
        var message = {"uid":uid,"content":msg,'formName':userName};
        var messageJson = JSON.stringify(message);
        websocket.send(messageJson);
    }
    //时间戳转化
    function formatDate(nows) {
        var now = new Date(nows);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    };
</script>